package runninbuddy;

public class DataExchanger implements Runnable {

	private final DataCombiner dataCombiner;
	private final DataStore dataStore;
	private final Updatable updatable; // TODO there's gotta be a better way
	private volatile boolean alive;

	public DataExchanger(DataCombiner dataCombiner, DataStore dataStore,
			Updatable updatable) {
		this.dataCombiner = dataCombiner;
		this.dataStore = dataStore;
		this.updatable = updatable;
		this.alive = true;
	}

	/*
	 * public void run() { if (dataCombiner == null) stop(); while (alive) {
	 * RunnerData data = null; try { data = dataCombiner.take(); } catch
	 * (InterruptedException e) { dbg("RunninBuddy.run: " + e.getMessage()); }
	 * if (data != null && data.bbLocation.isValid()) { if (dataStore != null)
	 * dataStore.put(data); update(data); } else {
	 * dbg("RunninBuddy.run: Location is invalid"); } } }
	 */

	public void run() {
		try {
			while (alive) {
				RunnerData data = dataCombiner.take();
				if (data.isValid()) {
					dataStore.put(data);
				}
				updatable.update(data);
			}
		} catch (InterruptedException e) {
			System.err.println("DataExchanger.run: " + e.getMessage());
		}
	}

	public void stop() {
		alive = false;
	}

}
